﻿Imports ajDataGridView = ajayumi.develop.VBasic.Win.Controls.DataGridView
Imports System.ComponentModel
Imports System.Windows.Forms
Imports ajayumi.develop.win32.WebResourcesCatcher.Service
Imports ajayumi.develop.VBasic.Core.Win

Public MustInherit Class DgvResourceBase
    Inherits ajDataGridView

#Region "Variables"
    Protected m_StopWatch As Stopwatch = Nothing
    Protected m_WebResourceCollection As WebResourceCollection = Nothing
    Private ReadOnly m_LockObj As Object = Nothing
#End Region


#Region "Properties"

    Private m_ResTaskInfo As ResTaskInfo
    Public Property ResTaskInfo() As ResTaskInfo
        Get
            Return m_ResTaskInfo
        End Get
        Set(ByVal value As ResTaskInfo)
            m_ResTaskInfo = value
        End Set
    End Property

#End Region

#Region "constructed function"
    Public Sub New()
        Me.AutoGenerateColumns = False
        Me.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
        Me.AllowUserToAddRows = False
        Me.AllowUserToDeleteRows = False
        Me.AllowUserToOrderColumns = True

        Me.m_WebResourceCollection = New WebResourceCollection()
        Me.DataSource = Me.m_WebResourceCollection

        ControlHelper.DoubleBuffered(Me, True)

        Me.m_LockObj = New Object()
    End Sub
#End Region

#Region "OnCreateControl"
    Protected Overrides Sub OnCreateControl()
        MyBase.OnCreateControl()

        Dim _ColChk As New DataGridViewCheckBoxColumn() With { _
            .HeaderText = String.Empty, .AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells}
        Dim _ColRowNum As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "编号", .ReadOnly = True, .DataPropertyName = "RowNum", _
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells}
        Dim _ColTitle As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "来源标题", .ReadOnly = True, .DataPropertyName = "Title"}
        Dim _ColUrl As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "资源链接", .ReadOnly = True, .DataPropertyName = "Url"}
        Dim _ColSourceUrl As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "来源地址", .ReadOnly = True, .DataPropertyName = "SourceUrl"}
        Dim _ColSaveFilePath As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "保存地址", .ReadOnly = True, .DataPropertyName = "SavePath"}
        Dim _ColSize As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "尺寸", .ReadOnly = True, .DataPropertyName = "Size"}
        Dim _ColProgressPercentage As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "进度", .ReadOnly = True, .DataPropertyName = "ProgressPercentage"}
        Dim _ColCreationTime As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "创建时间", .ReadOnly = True, .DataPropertyName = "CreationTime"}
        Dim _ColStatus As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "状态", .ReadOnly = True, .DataPropertyName = "ResStatus", .Name = "colResStatus"}
        Dim _ColInformation As New System.Windows.Forms.DataGridViewTextBoxColumn() With { _
            .HeaderText = "信息", .ReadOnly = True, .DataPropertyName = "Information"}

        Me.Columns.Clear()
        Me.Columns.AddRange(New DataGridViewColumn() {_ColChk, _
                                                      _ColRowNum, _
                                                      _ColTitle, _
                                                      _ColUrl, _
                                                      _ColSourceUrl, _
                                                      _ColSaveFilePath, _
                                                      _ColSize, _
                                                      _ColProgressPercentage, _
                                                      _ColCreationTime, _
                                                      _ColStatus, _
                                                      _ColInformation})

    End Sub

#End Region

#Region "event"

    ''' <summary>
    ''' 当前节点加载子节点时调用
    ''' </summary>
    ''' <remarks></remarks>
    <Description("项加载进度事件")> _
    Public Event LoadProgressChanged As ProgressChangedEventHandler
    Protected Overridable Sub OnLoadProgress(ByVal e As ProgressChangedEventArgs)
        If e IsNot Nothing Then
            RaiseEvent LoadProgressChanged(Me, e)
        End If
    End Sub


    ''' <summary>
    ''' 当前节点加载完子节点时调用
    ''' </summary>
    <Description("项加载完成事件")> _
    Public Event LoadCompleted As AsyncCompletedEventHandler
    Protected Overridable Sub OnLoadComplete(ByVal e As AsyncCompletedEventArgs)
        If e IsNot Nothing Then
            RaiseEvent LoadCompleted(Me, e)
        End If
    End Sub


#End Region

#Region "override"

#End Region

#Region "private method"

#End Region

#Region "protected method"

    ''' <summary>
    ''' 加载项
    ''' </summary>
    ''' <param name="lst"></param>
    ''' <remarks></remarks>
    Protected MustOverride Sub LoadItems(ByVal lst As List(Of WebResourceInfo))

    ''' <summary>
    ''' 加载项完成时的回调方法
    ''' </summary>
    ''' <param name="ar"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub LoadItems_Callback(ByVal ar As IAsyncResult)
        Dim _LoadItemHandler As Action(Of List(Of WebResourceInfo)) = DirectCast(ar.AsyncState, Action(Of List(Of WebResourceInfo)))
        _LoadItemHandler.EndInvoke(ar)

        Me.OnLoadComplete(New System.ComponentModel.AsyncCompletedEventArgs(Nothing, False, Me))
    End Sub

    ''' <summary>
    ''' 获取DataGridView中，勾选的实体对象记录
    ''' </summary>
    ''' <typeparam name="T">实体对象</typeparam>
    ''' <param name="dgv">DataGridView控件</param>
    ''' <param name="chkIndex">复选框的列序号</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Function GetCheckedItems(Of T)(dgv As ajDataGridView, chkIndex As Integer) As List(Of T)
        Dim _List As New List(Of T)()
        dgv.EndEdit()
        For Each item As DataGridViewRow In dgv.Rows
            If item.Cells(chkIndex).Value IsNot Nothing AndAlso DirectCast(item.Cells(chkIndex).Value, Boolean) Then
                Dim _Item As T = DirectCast(item.DataBoundItem, T)
                _List.Add(_Item)
            End If
        Next
        Return _List
    End Function

#End Region

#Region "public method"

    ''' <summary>
    ''' 加载
    ''' </summary>
    Public Sub LoadAsync(ByVal lst As List(Of WebResourceInfo))
        Dim _LoadItemsHandler As New Action(Of List(Of WebResourceInfo))(AddressOf Me.LoadItems)
        _LoadItemsHandler.BeginInvoke(lst, New AsyncCallback(AddressOf Me.LoadItems_Callback), _LoadItemsHandler)
    End Sub

    Public Sub [ClearAll]()
        Me.Invoke(New Action(AddressOf Me.m_WebResourceCollection.Clear))
    End Sub

    ''' <summary>
    ''' 全部勾选
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub [CheckAll]()

    End Sub

    ''' <summary>
    ''' 取消全部勾选
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub UnCheckAll()

    End Sub

    ''' <summary>
    ''' 移除勾选项
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RemoveCheckedItems()
        Dim _Func As New Func(Of ajDataGridView, Integer, List(Of WebResourceInfo))(AddressOf Me.GetCheckedItems(Of WebResourceInfo))
        _Func.BeginInvoke(Me, 0, _
                          New AsyncCallback(Sub(ar As IAsyncResult)
                                                Dim _SubFunc As Func(Of ajDataGridView, Integer, List(Of WebResourceInfo)) = DirectCast(ar.AsyncState, Func(Of ajDataGridView, Integer, List(Of WebResourceInfo)))
                                                Dim _List As List(Of WebResourceInfo) = _SubFunc.EndInvoke(ar)

                                                _List.ForEach(Sub(item As WebResourceInfo)
                                                                  Me.Invoke(New Action(Of WebResourceInfo)(AddressOf Me.m_WebResourceCollection.Remove), New Object() {item})
                                                              End Sub)
                                            End Sub), _
                          _Func)
    End Sub

    ''' <summary>
    ''' 移除已下载完成项
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RemoveDownloadedItems()
        Dim _List As List(Of WebResourceInfo) = Nothing
        Dim _Func As New Func(Of List(Of WebResourceInfo))(Function()
                                                               Dim _ResourceInfos = From res In Me.m_WebResourceCollection _
                                                                                    Where res.ResStatus = ResourceStatus.Downloaded _
                                                                                    Select res
                                                               _List = New List(Of WebResourceInfo)()
                                                               _List.AddRange(_ResourceInfos)
                                                               Return _List
                                                           End Function)

        '_Func.BeginInvoke(New AsyncCallback(Sub(ar As IAsyncResult)
        '                                        Try
        '                                            Dim _SubFunc As Func(Of List(Of WebResourceInfo)) = DirectCast(ar.AsyncState, Func(Of List(Of WebResourceInfo)))
        '                                            Dim _List As List(Of WebResourceInfo) = _SubFunc.EndInvoke(ar)

        '                                            _List.ForEach(Sub(item As WebResourceInfo)
        '                                                              Me.Invoke(New Action(Of WebResourceInfo)(AddressOf Me.m_WebResourceCollection.Remove), New Object() {item})
        '                                                          End Sub)
        '                                        Catch ex As Exception
        '                                            Console.WriteLine("RemoveDownloadedItems 发生错误，错误信息：\n{0}", ex.Message)
        '                                        End Try
        '                                    End Sub), _
        '                  _Func)

        _List = _Func.Invoke()
        SyncLock Me.m_LockObj
            _List.ForEach(Sub(item As WebResourceInfo)
                              Me.Invoke(New Action(Of WebResourceInfo)(AddressOf Me.m_WebResourceCollection.Remove), New Object() {item})
                          End Sub)
        End SyncLock




        'Dim _List As List(Of DataGridViewRow) = Nothing
        'Dim _Func As New Func(Of List(Of DataGridViewRow))(Function()
        '                                                       Dim _Rows = From row As DataGridViewRow In Me.Rows _
        '                                                                   Where DirectCast(row.DataBoundItem, WebResourceInfo).ResStatus = ResourceStatus.Downloaded _
        '                                                                   Select row
        '                                                       _List = New List(Of DataGridViewRow)()
        '                                                       _List.AddRange(_Rows)
        '                                                       Return _List
        '                                                   End Function)
        '_List = _Func.Invoke()
        '_List.ForEach(Sub(item As DataGridViewRow)
        '                  Me.Invoke(New Action(Of DataGridViewRow)(AddressOf Me.Rows.Remove), New Object() {item})
        '              End Sub)
    End Sub

#End Region

End Class
